import types from './types'
import { getRepos } from '@/api'

const getReposAction = async ({ commit, state }, {
  page,
  perPage,
  newData = false
} = {}) => {
  page = page || state.page + 1
  perPage = perPage || state.perPage
  commit(types.SET_PAGE_INFO, { reposLoading: true })
  const repos = await getRepos({
    page,
    per_page: perPage
  })
  if (newData) {
    commit(types.SET_REPOS, repos)
  } else {
    commit(types.SET_REPOS, [].concat(state.repos, repos))
  }
  commit(types.SET_PAGE_INFO, {
    reposLoading: false,
    reposLoaded: repos.length < perPage,
    page,
    perPage
  })
}

const setCurrentRepoAction = ({ commit }, params) => {
  commit(types.SET_CURRENT_REPO, params)
}

export default {
  getRepos: getReposAction,
  setCurrentRepo: setCurrentRepoAction
}
